<template>
  <div class="app-continer">
    <!-- 搜索区域 -->
    <el-form :model="searchForm" :inline="true" style="margin-bottom: 20px;">
      <el-row>
        <el-col>
          <el-form-item>
            <el-input
              v-model="searchForm.batchNumber"
              placeholder="样品批次编号"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格区域 -->
    <el-table
      :data="batchData"
      stripe
      border
      style="width: 100%"
      :header-cell-style="{ background: '#ECF3FC' }"
    >
      <template slot="empty">
        <div class="table_empty">
          <div class="empty_tips">
            <span>暂无信息</span>
          </div>
        </div>
      </template>

      <el-table-column type="index" width="50" align="center" label="序号" />
      <el-table-column
        prop="projectName"
        label="项目名称"
        width="200px"
        align="center"
      />
      <el-table-column
        prop="inspectionName"
        label="受检单位"
        width="250px"
        align="center"
      />
      <el-table-column
        prop="batchNumber"
        label="样品批次编号"
        min-width="100"
        align="center"
      />
      <el-table-column
        prop="sampleCount"
        label="分批样品数量"
        align="center"
      />
      <el-table-column
        prop="sampleNos"
        label="样品号"
        min-width="300"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="factorCount"
        label="分批检测因子数量"
        align="center"
      />
      <el-table-column
        prop="factorNames"
        label="检测因子名称"
        min-width="300"
        align="center"
      >
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="240" align="center">
        <template slot-scope="{ row }">
          <el-button type="text" @click="handleView(row)">查看</el-button>
          <div class="erc-divider-vertical" />
          <el-button type="text" @click="handleModify(row)">修改批次</el-button>
          <div class="erc-divider-vertical" />
          <el-button type="text" @click="handleCancel(row)">取消批次</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div style="float: right; margin-top: 20px;">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="searchForm.pageNumber"
        :limit.sync="searchForm.pageSize"
        @pagination="handleSearch"
      />

      <el-dialog
        :title="`修改实验室样品批次 - ${currentBatch.batchNumber}`"
        :visible.sync="dialogVisible"
        width="90%"
        @close="resetDialog"
      >
        <div class="batch-edit-container">
          <!-- 可选分批样品 -->
          <div class="section">
            <h3>可选分批样品</h3>
            <el-table
              :data="availableSamples"
              stripe
              border
              style="width: 100%"
              max-height="400"
              :header-cell-style="{ background: '#ECF3FC' }"
            >
              <el-table-column
                type="index"
                width="50"
                align="center"
                label="序号"
              />
              <el-table-column
                prop="secdClassName"
                label="检测对象"
                align="center"
              />
              <el-table-column
                prop="factorName"
                label="检测因子"
                align="center"
              />
              <el-table-column
                prop="standardNo"
                label="标准号"
                align="center"
              />
              <el-table-column
                prop="standardName"
                label="检测标准"
                align="center"
              />
              <el-table-column
                prop="analysisMethod"
                label="分析方法"
                align="center"
              />
              <el-table-column
                prop="storeTime"
                label="入库时间"
                align="center"
              />
              <el-table-column
                prop="checkStatus"
                label="检测状态"
                align="center"
              >
                <template slot-scope="{ row }">
                  <el-tag :type="row.checkStatus | statusQualityFilter">
                    {{ CHECK_STATUS[row.checkStatus] }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="sampleNo"
                label="样品编号"
                align="center"
              />
              <el-table-column
                label="操作"
                fixed="right"
                width="100"
                align="center"
              >
                <template slot-scope="{ row }">
                  <el-button
                    type="text"
                    size="small"
                    v-if="row.checkStatus === '1'"
                    @click="addSampleToBatch(row)"
                  >
                    加入批次
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 已分批样品 -->
          <div class="section" style="margin-top: 30px;">
            <h3>已分批样品</h3>
            <el-table
              :data="batchedSamples"
              stripe
              border
              style="width: 100%"
              max-height="400"
              :header-cell-style="{ background: '#ECF3FC' }"
            >
              <el-table-column
                type="index"
                width="50"
                align="center"
                label="序号"
              />
              <el-table-column
                prop="secdClassName"
                label="检测对象"
                align="center"
              />
              <el-table-column
                prop="factorName"
                label="检测因子"
                align="center"
              />
              <el-table-column
                prop="standardNo"
                label="标准号"
                align="center"
              />
              <el-table-column
                prop="standardName"
                label="检测标准"
                align="center"
              />
              <el-table-column
                prop="analysisMethod"
                label="分析方法"
                align="center"
              />
              <el-table-column
                prop="sampleNo"
                label="样品编号"
                align="center"
              />
              <el-table-column
                label="操作"
                fixed="right"
                width="100"
                align="center"
              >
                <template slot-scope="{ row }">
                  <el-button
                    type="text"
                    size="small"
                    @click="removeSampleFromBatch(row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmModifyBatch"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import * as batchesServer from "@/api/batches";
import * as checkServer from "@/api/check";
import Pagination from "@/components/Pagination";
const CHECK_STATUS = {
  "0": "待领样",
  "1": "待分批"
};
export default {
  components: { Pagination },
  props: {
    checkTaskId: {
      type: String,
      default: ""
    }
  },
  filters: {
    statusQualityFilter(status) {
      if (status === "0") {
        return "info";
      } else if (status === "1") {
        return "";
      }
    }
  },
  data() {
    return {
      CHECK_STATUS,
      searchForm: {
        sampleNo: "",
        checkTaskId: "",
        jobId: "",
        pageNumber: 1,
        pageSize: 10
      },
      batchData: [],
      total: 0,
      dialogVisible: false,
      currentBatch: {}, // 当前编辑的批次
      availableSamples: [], // 可选样品
      batchedSamples: [] // 已分批样品
    };
  },
  created() {
    if (this.checkTaskId && this.checkTaskId.length > 0) {
      this.searchForm.checkTaskId = this.checkTaskId;
    }
    this.searchForm.jobId = this.$route.query.jobId || "";
    this.handleSearch();
  },
  methods: {
    handleSearch() {
      batchesServer.findCheckTaskBatchByCondition(this.searchForm).then(res => {
        console.log("query", res);
        if (res.code == 200 && res.result) {
          this.batchData = res.result.records;
          this.total = res.result.total;
        }
      });
    },

    handleModify(row) {
      this.currentBatch = { ...row };
      this.loadAvailableAndBatchedSamples(row); // 加载对应数据
      this.dialogVisible = true;
    },

    loadAvailableAndBatchedSamples(row) {
      if (this.checkTaskId && this.checkTaskId.length > 0) {
        checkServer.findCheckTaskGroupByCondition(this.searchForm).then(res => {
          if (res.code === 200) {
            this.availableSamples = res.result.records;
            this.total = res.result.total;
          }
        });
      }

      if (row.batchNumber && row.batchNumber != "") {
        batchesServer.getCheckFactorByBatchNumber(row.batchNumber).then(res => {
          if (res.code === 200) {
            this.batchedSamples = res.result;
          }
        });
      }
    },

    addSampleToBatch(sample) {
      if (
        this.batchedSamples.some(s => s.checkFactorId === sample.checkFactorId)
      ) {
        this.$message.warning("该样品已在批次中");
        return;
      }
      this.batchedSamples.push({ ...sample });
      this.availableSamples = this.availableSamples.filter(
        s => s.checkFactorId !== sample.checkFactorId
      );
    },

    removeSampleFromBatch(sample) {
      this.$confirm("确定要从批次中移除该样品吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.batchedSamples = this.batchedSamples.filter(
          s => s.checkFactorId !== sample.checkFactorId
        );
        this.availableSamples.push({ ...sample, checkStatus: "1" });
        this.$message.success("样品已移除");
      });
    },

    confirmModifyBatch() {
      this.$confirm("确定批量合并批次?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const checkFactorIds = this.batchedSamples.map(i => {
          return i.checkFactorId;
        });
        batchesServer
          .checkFactorUpBatch({
            checkFactorId: checkFactorIds.toString(","),
            batchNumber: this.currentBatch.batchNumber,
            jobId: this.currentBatch.jobId
          })
          .then(res => {
            if (res.code == 200) {
              this.$notify({
                title: "成功",
                message: res.message,
                type: "success"
              });
              this.handleSearch();
              this.dialogVisible = false;
            } else {
              this.$notify({
                title: "失败",
                message: res.message,
                type: "error"
              });
            }
          });
      });
    },

    resetDialog() {
      this.currentBatch = {};
      this.availableSamples = [];
      this.batchedSamples = [];
    },
    handleCancel(row) {
      this.$confirm("确定要取消该批次吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        batchesServer
          .cancelCheckFactorBatch({
            batchNumber: row.batchNumber,
            jobId: row.jobId
          })
          .then(res => {
            if (res.code === 200) {
              this.$notify({
                title: "成功",
                message: res.message,
                type: "success"
              });
              this.handleSearch();
            } else {
              this.$notify({
                title: "失败",
                message: res.message,
                type: "error"
              });
            }
          });
      });
    },
    handleView(row) {
      this.$router
        .push({
          name: "BatchDetail",
          params: {
            batchNumber: row.batchNumber,
            checkFactorId: row.checkFactorId,
            checkFactorIds: row.checkFactorIds,
            jobId: this.searchForm.jobId,
            checkTaskId: this.checkTaskId
          }
        })
        .catch(err => {
          console.error("路由跳转失败:", err);
          this.$message.error("页面跳转失败");
        });
    }
  }
};
</script>

<style scoped lang="scss">
.el-form-item {
  margin-bottom: 0;
}

.el-form-item__label {
  font-weight: normal;
}

.el-table {
  margin-bottom: 20px;
}

.table_empty {
  text-align: center;
  padding: 40px 0;
}

.empty_tips {
  color: #999;
  font-size: 14px;
}

.erc-divider-vertical {
  display: inline-block;
  width: 1px;
  height: 14px;
  background-color: #ebeef5;
  vertical-align: middle;
  margin: 0 10px;
}

::v-deep .el-table th {
  background-color: #ecf3fc !important;
  color: #333;
  font-weight: bold;
}

::v-deep .el-table td {
  padding: 12px 0;
}

::v-deep .el-table .cell {
  white-space: pre-line;
  word-break: break-all;
}
.batch-edit-container {
  .section {
    margin-bottom: 20px;
    h3 {
      font-size: 16px;
      color: #333;
      margin-bottom: 10px;
      padding-left: 10px;
      border-left: 4px solid #409eff;
    }
  }

  .el-table {
    margin-bottom: 20px;
  }
}
</style>
